package com.daoshu.mds.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.mds.constants.RoleType;
import com.daoshu.mds.system.mapper.RoleMapper;
import com.daoshu.mds.system.service.IOrganizationService;
import com.daoshu.mds.system.service.IRoleDataService;
import com.daoshu.mds.system.service.IRoleService;
import com.daoshu.system.bo.RoleBo;
import com.daoshu.system.entity.OrganizationEntity;
import com.daoshu.system.entity.RoleDataEntity;
import com.daoshu.system.entity.RoleEntity;
import com.daoshu.system.utils.RequestUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements IRoleService {

	@Autowired
	private IRoleDataService roleDataService;
	
	@Autowired
	private IOrganizationService organizationService;
	
	@Autowired
	private RequestUtils requestUtils;
	
	@Override
	public IPage<RoleEntity> getPage(RoleBo roleBo) {
		RoleEntity condition = new RoleEntity();
		BeanUtils.copyProperties(roleBo, condition);
		QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<RoleEntity>(condition);
		String name = condition.getName();
		condition.setName(null);
		if (StringUtils.isNotEmpty(name)) {
			queryWrapper.lambda().like(RoleEntity::getName, "%" + name + "%");
		}
		return this.page(new Page<>(roleBo.getStart(), roleBo.getSize()), queryWrapper);
	}

	@Override
	public RoleEntity saveOrUpd(RoleEntity entity) {
		if (StringUtils.isNotEmpty(entity.getId())) {
			roleDataService.remove(new QueryWrapper<RoleDataEntity>().eq("role_id_", entity.getId()));
		}
		entity.setCreateTime(new Date());
		entity.setCreatorId(requestUtils.getCurrentUser().getPersonId());
		this.saveOrUpdate(entity);
		List<String> orgIds = getOrgIdsByType(entity);
		RoleDataEntity roleDataEntity = new RoleDataEntity();
		roleDataEntity.setRoleId(entity.getId());
		roleDataEntity.setOrgIds(String.join(",", orgIds));
		roleDataService.save(roleDataEntity);
		return entity;
	}
	@Override
	public List<RoleEntity> getOrgsByType (Integer orgSort) {
		List<Integer> sorts  = null;
		//组织种类：1 市局情报中心，2 市局警种，3 分局，4 派出所  
		if(1==orgSort) {
			sorts  = Arrays.asList(1);
		}
		if(2==orgSort) {
			sorts  = Arrays.asList(2,5);
		}
		if(3==orgSort) {
			sorts  = Arrays.asList(3,6);
		}
		if(4==orgSort) {
			sorts  = Arrays.asList(4);
		}
		QueryWrapper<RoleEntity> wrapper = new QueryWrapper<>();
		wrapper.in("role_type_", sorts);
        return this.list(wrapper);
		
	}

	@Override
	public List<RoleEntity> getListByRegionId(String regionId) {
		List<OrganizationEntity> organizationEntities = organizationService.getListByRegionId(regionId);
		if(null == organizationEntities || organizationEntities.size()<=0) return null;
		/* 权限配置原则：
		*  1 情报中心一下都可以配置：情报中心权限;
		*  2 支队 及支队之下单位都可以配置：市局警种 和 市局审核警种
		*  3 分局：<1> 派出所及派出所之下配置：派出所
		*          <2> 除派出所和派出所的下属单位之外的 都配置：分局 和 分局审核
		* */
		List<String> shortNames = organizationEntities.stream().map(OrganizationEntity::getShortName).collect(Collectors.toList());
		List<Integer> sorts  = null;
		// 判断是否为情报中心用户
		if(judgeUserRole(shortNames,"警令部","警令部情报信息中心")||shortNames.size()==1)
			sorts= Arrays.asList(1);
		if(shortNames.size()==2){
			if("昆明市公安局".equals(shortNames.get(1))){
				sorts= Arrays.asList(1);
			}
		}
		if(judgeUserRole(shortNames,"支队")) sorts = Arrays.asList(2,5);
		if(judgeUserRole(shortNames,"分局")||judgeUserRole(shortNames,"县局")||judgeUserRole(shortNames,"市局")){
			if(judgeUserRole(shortNames,"派出所")){
				sorts = Arrays.asList(4);
			}else{
				sorts = Arrays.asList(3,6);
			}
		}
		if(null == sorts) return new ArrayList<>();
		QueryWrapper<RoleEntity> wrapper = new QueryWrapper<>();
		wrapper.in("role_type_", sorts);
		return this.list(wrapper);
	}

	private boolean judgeUserRole(List<String> shortNames, String...args) {
		List<Boolean> flag = new ArrayList<>();
		for(String arg : args){
			for(String shortName : shortNames){
				if(shortName.indexOf(arg)>=0){
					flag.add(true);
					break;
				}
			}
		}
		if(flag.size()<args.length) return false;
		return true;
	}

	private List<String> getOrgIdsByType (RoleEntity entity) {
		List<String> result = new ArrayList<String>();
		if (RoleType.COSTOMIZE_ORG_DATA.getType() == entity.getRoleType()) {
			return entity.getOrgIds();
		} else if (RoleType.ADMIN_ORG_DATA.getType() == entity.getRoleType()) {
			List<OrganizationEntity> entitys = organizationService.list(new QueryWrapper<OrganizationEntity>().eq("available_", 1));
			entitys.forEach(e -> result.add(e.getId()));
		} else if (RoleType.OWNER_ADMIN_ORG_DATA.getType() == entity.getRoleType()) {
			return organizationService.getAllChild(requestUtils.getCurrentUser().getOrgId(), true, false);
		} else if (RoleType.OWNER_ORG_DATA.getType() == entity.getRoleType()) {
			result.add(requestUtils.getCurrentUser().getOrgId());
		}
		return result;
	}
	
	@Override
	public int removeByIds(String ids) {
		List<String> idArr = Arrays.asList(ids.split(","));
		this.removeByIds(idArr);
		roleDataService.remove(new QueryWrapper<RoleDataEntity>().in("role_id_", idArr));
		return idArr.size();
	}
	public static void main(String[] args) {
		System.out.println(RoleType.ADMIN_ORG_DATA.getType());
		System.out.println(RoleType.OWNER_ADMIN_ORG_DATA.getType());
		System.out.println(RoleType.OWNER_ORG_DATA.getType());
		System.out.println(RoleType.COSTOMIZE_ORG_DATA.getType());

		
	}

}
